package com.example.nio.network.reactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年08月07日 20:40:00
 * @Description   Acceptor主要用于处理连接操作
 * 注册时丢了一个附加对象进去，这个附加对象会在选择器选择到此通道上时，可以通过`attachment()`方法进行获取
 */
public class Acceptor implements Runnable{

    private final ServerSocketChannel serverChannel;
    private final Selector selector;

    public Acceptor(ServerSocketChannel serverChannel, Selector selector) {
        this.serverChannel = serverChannel;
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            SocketChannel socketChannel = serverChannel.accept();
            System.out.println("客户端已连接，IP地址为：" + socketChannel.getRemoteAddress());
            //现在连接就建立好了，接着我们需要将连接注册到选择器，比如我们需要当这个连接有内容可读时就进行处理，注册前先将read设置为非阻塞
            socketChannel.configureBlocking(false);
            // 将socketChannel注册到selector上，监听读事件
            socketChannel.register(selector, SelectionKey.OP_READ,new Handler(socketChannel));
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }


}
